<template>
    <div id="add-edit-model" class="page-public-s">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable :close-on-click-modal="false" :close-on-press-escape="false"
            width="50%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="100px" :rules="rules">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="工种名称" prop="v_WorkName">
                            <el-input v-model="ruleForm.v_WorkName" type="text" placeholder="工种名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="工种类别">
                            <el-select 
                                v-model="ruleForm.c_WorkType" 
                                filterable 
                                class="m-2" 
                                placeholder="请选择搜索方式" 
                                @change="typeChange"
                            >
                                <el-option
                                    v-for="item in typeOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                            <!-- <el-input v-model="ruleForm.V_Work_Name" placeholder="工种名称" clearable /> -->
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="工种描述">
                            <el-input type="textarea" v-model="ruleForm.v_WorkTypeDescribe" placeholder="工种名称" clearable />
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="启用状态">
                            <el-switch
                                v-model="ruleForm.n_isValid"
                                active-color="#07AAF9"
                                inactive-color="#FF5F33"
                                inline-prompt
                                active-text="启用"
                                inactive-text="禁用"
                            />
                        </el-form-item>
                    </el-col> -->
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="备注">
                            <el-input type="textarea" v-model="ruleForm.v_Remake" placeholder="备注" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取消</el-button>
                <el-button :loading="repeatDis" :disabled="repeatDis" @click="submitForm(ruleFormRef)" type="primary">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue';
import { FormInstance, FormRules , ElMessage, ElButton, ElCol, ElDatePicker, ElDialog, ElDivider, ElForm, ElFormItem, ElInput, ElOption, ElRadio, ElRow, ElSelect, ElTable, ElTableColumn } from 'element-plus';
import { WorkTypeAdd , WorkTypeUpdate } from '/@/api/centerControl/oms';
import useCurrentInstance from '/@/utils/hook/useCurrentInstance';
import { getSupplierCountryRegionApi } from '/@/api/centerControl/allInterface';

/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    n_Id?: Number | String, // 唯一识别编码
    v_WorkName:String, // 工种名称
    c_WorkType: String, // 工种类别
    v_WorkTypeDescribe: String, // 工种描述
    n_isValid: Boolean, // 状态（启用/禁用）
    v_Remake: String, // 备注
}
export default defineComponent( {
    name: 'add-edit-model',
    components: {},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        // const { proxy } = useCurrentInstance();
        // const $t = proxy.$t;

        const titleCon = ref()
        const ruleFormRef = ref()

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            v_WorkName: [
				{ required: true, message: '请输入工种名称', trigger: 'blur' },
			],
            v_WorkTypeDescribe: [
                { required: true, message: '请输入工种描述', trigger: 'blur' }
            ],
        })

        const typeChange = (val:any) => {
            console.log(val,'val')
        }

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            ctx.emit('cancelUseClick')
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => {
                if(valid){
                    const setObj = toRaw(state.ruleForm)
                    let param:any = {}
                    param.n_isValid = setObj.n_isValid ? 1 : 2
                    let sendVal = { ...setObj , ...param }
                    for(let i in sendVal){
                        console.log(sendVal[i],i)
                        if(sendVal[i] == null){
                            sendVal[i] = ''
                        }
                    }
                    if(!setObj.n_Id){
                        state.repeatDis = true
                        let res:any = await WorkTypeAdd(sendVal)
                        if(res.success){
                            ctx.emit('controlUseClick','success')
                            ctx.emit('updateData')
                            state.repeatDis = false
                        }
                    }else{
                        state.repeatDis = true
                        let res:any = await WorkTypeUpdate(sendVal)
                        if(res.success){
                            ctx.emit('controlUseClick','success')
                            ctx.emit('updateData')
                            state.repeatDis = false
                        }
                    }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                state.repeatDis = false
                if(props.repairInfo !== ''){
                    titleCon.value = '编辑'
                    let setPara:any = {}
                    let getData = JSON.parse(props.repairInfo)
                    getData.n_isValid === 1 ? setPara.n_isValid = true : setPara.n_isValid = false
                    const {n_isValid , ...setData} = getData
                    state.ruleForm = { ...setPara , ...setData }
                }else{
                    titleCon.value = '新增'
                    state.ruleForm = {
                        v_WorkName: '', // 工种名称
                        c_WorkType: '', // 工种类别
                        v_WorkTypeDescribe: '', // 工种描述
                        n_isValid: true, // 状态（启用/禁用）
                        v_Remake: '', // 备注
                    }
                }
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

       const  typeOptions = ref([])
        onMounted( async () => {
            const res = await getSupplierCountryRegionApi({ TypeCode: 'omsJobtype' });
            typeOptions.value = res.data.map((i: any) => {
		return {
			label: i.value,
			value: i.id,
		};
	});
        })

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            typeOptions,
            typeChange,
        }
    },
} )
</script>
<style scoped lang="scss">
    :deep(.el-select){
        width: 100%;
    }
</style>